package com.example.arrange;

import com.example.util.CommonUtils;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;

public class ThenComposeDemo2 {

    public static void main(String[] args) {
        CommonUtils.printThreadLog("main start");

        String path = "filter_words.txt";

        // 推荐方法
        CompletableFuture<String[]> filterWordsFuture = readWordArrayFuture(path);
        System.out.println(Arrays.toString(filterWordsFuture.join()));


        CompletableFuture<String[]> filterWordsFuture2 = CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读取文件：" + path);
            return CommonUtils.readFile(path);
        }).thenCompose(content -> {
            CommonUtils.printThreadLog("thenCompose的方法内部调用（lambda）");
            return CompletableFuture.supplyAsync(() -> {
                CommonUtils.printThreadLog("将内容转为字符串数组");
                return content.split(",");
            });
        });
        System.out.println(Arrays.toString(filterWordsFuture2.join()));


        CompletableFuture<String[]> filterWordsFuture3 = CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读取文件：" + path);
            return CommonUtils.readFile(path);
        }).thenCompose(new Function<String, CompletableFuture<String[]>>() {
            @Override
            public CompletableFuture<String[]> apply(String content) {
                CommonUtils.printThreadLog("thenCompose的方法内部调用（Function）");
                return splitFuture(content);
            }
        });
        System.out.println(Arrays.toString(filterWordsFuture3.join()));


        CommonUtils.printThreadLog("main end");
    }

    private static CompletableFuture<String> readFileFuture(String path) {
        return CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读取文件：" + path);
            return CommonUtils.readFile(path);
        });
    }

    private static CompletableFuture<String[]> splitFuture(String content) {
        return CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("将内容转为字符串数组");
            return content.split(",");
        });
    }

    private static CompletableFuture<String[]> readWordArrayFuture(String path) {
        return readFileFuture(path).thenCompose(ThenComposeDemo2::splitFuture);
    }
}
